package cn.hairui.blog.controller;

import cn.hairui.blog.configure.WebLog;
import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.entity.Albumimg;
import cn.hairui.blog.entity.Myinfo;
import cn.hairui.blog.entity.User;
import cn.hairui.blog.service.AlbumimgService;
import cn.hairui.blog.service.MyinfoService;
import cn.hairui.blog.util.DateUtil;
import cn.hairui.blog.util.BlogUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 相册照片表 前端控制器
 * </p>
 *
 * @author laoganbu
 * @since 2020-04-15
 */
@Controller
public class AlbumimgController {
    @Autowired
    private MyinfoService myinfoService;
    @Autowired
    private AlbumimgService albumimgService;

    @Value("${upload_path}")
    private String uploadPath;

    @Value("${virtual_upload_path}")
    private String virtualUploadPath;

    //// ==========================前台==============================///////

    @GetMapping("/albumimg/{aid}")
    @WebLog(description = "查看相册图片")
    public String albumimg(@PathVariable int aid, HttpServletRequest request, Model model) {
        /*
         * User user = (User)
         * request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME); if(user
         * != null && PubConstant.USER_TYPE_SUPER_ADMIN.equals(user.getType())){
         *
         * }
         */

        Myinfo myinfo = myinfoService.getById(PubConstant.MY_INFO_ID);
        model.addAttribute("myinfo", myinfo);

        List<Albumimg> albumImgList = albumimgService.findImagesByAlbumId(aid);
        model.addAttribute("albumImgs", albumImgList);
        return "albumimg";
    }

    //// ==========================后台==============================///////
    // 内容编辑页面
    @RequestMapping(value = "/manage/albumimg/img")
    public String img(HttpServletRequest request, Model model) {
        int id = Integer.parseInt(request.getParameter("id"));
        Myinfo myinfo = myinfoService.getById(PubConstant.MY_INFO_ID);
        model.addAttribute("myinfo", myinfo);

        model.addAttribute("albumId", id);
        return "page/album/imgList";
    }

    // 列表数据
    @RequestMapping(value = "/manage/albumimg/data")
    @ResponseBody
    public String data(HttpServletRequest request, Model model) {
        Map map = new HashMap<Object, Object>();
        /*
         * int pageSize = 5;//默认每页显示5条记录 int pageNum = 1; try { pageNum =
         * Integer.parseInt(request.getParameter("page")); pageSize =
         * Integer.parseInt(request.getParameter("limit")); } catch (Exception e) { }
         * PageHelper.startPage(pageNum, pageSize);
         */
        int id = Integer.parseInt(request.getParameter("id"));
        List<Map> albumList = albumimgService.getByAlbumId(id);

        /* PageInfo<Map> pageInfo = new PageInfo<Map>(albumList); */

        map.put("data", albumList);
        map.put("title", "照片管理");
        map.put("id", "Images");
        map.put("start", 0);

        return JSONUtils.toJSONString(map);
    }

    // 新增数据
    @RequestMapping(value = "/mamage/albumimg/uploadImg")
    @ResponseBody
    public String add(HttpServletRequest request) {
        Map map = new HashMap<Object, Object>();
        int albumId = Integer.parseInt(request.getParameter("id"));
        Albumimg albumimg = new Albumimg();

        albumimg.setAlbumId(albumId);
        albumimg.setAddTime(DateUtil.getCurrentTime());

        File targetPath = new File(uploadPath + PubConstant.ALBUM_DIR + PubConstant.IMAGES_DIR);
        if (!targetPath.exists()) {
            targetPath.mkdirs();
        }
        // 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    String fileName = file.getOriginalFilename();
                    String suffixName = fileName.substring(fileName.lastIndexOf("."));
                    // 重新生成文件名
                    String perfix = BlogUtil.getUUIDUpperCase();
                    fileName = perfix + suffixName;

                    albumimg.setImgName(perfix);
                    albumimg.setImgPath(fileName);
                    String path = uploadPath + PubConstant.ALBUM_DIR + PubConstant.IMAGES_DIR + fileName;
                    // 上传
                    try {
                        file.transferTo(new File(path));
                        albumimgService.saveOrUpdate(albumimg);// 保存数据
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        map.put(PubConstant.flag, PubConstant.success);
        return JSONUtils.toJSONString(map);
    }

    // 删除操作
    @RequestMapping(value = "/manage/albumimg/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@Param(value = "name") String name, HttpServletRequest request) {
        Map map = new HashMap();
        // 判断权限
        User user = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (user != null && PubConstant.USER_TYPE_SUPER_ADMIN.equals(user.getType())) {
            // 查询
            QueryWrapper<Albumimg> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("IMG_NAME", name);
            Albumimg albumimg = (Albumimg) albumimgService.getObj(queryWrapper);
            albumimgService.removeByName(name);
            try {
                // 删除文件
                String fileName = albumimg.getImgPath();
                File file = new File(uploadPath + PubConstant.ALBUM_DIR + PubConstant.IMAGES_DIR + fileName);
                if (file.exists() && fileName != null && !"".equals(fileName)) {
                    file.delete();
                }
            } catch (Exception e) {
            }
            map.put(PubConstant.flag, PubConstant.success);
        }
        return JSONUtils.toJSONString(map);
    }
}
